package indi.zhifa.core.multidatasource.core;

import indi.zhifa.core.common.web.entity.exception.ServiceException;

import javax.sql.DataSource;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;

public class RoutingDataSourceMemo {
    private Map<String,ZfRoutingDataSource> mRoutingDataSource;

    public RoutingDataSourceMemo() {
        mRoutingDataSource = new ConcurrentHashMap<String,ZfRoutingDataSource>();
    }
    public ZfRoutingDataSource createRoutingDataSource(String pKey, Map<Object, Object> pDataSourceMap, DataSource pPrimaryDataSource) {
        ZfRoutingDataSource zfRoutingDataSource = new ZfRoutingDataSource();
        zfRoutingDataSource.setTargetDataSources(pDataSourceMap);
        zfRoutingDataSource.setDefaultTargetDataSource(pPrimaryDataSource);
        zfRoutingDataSource.initialize();
        mRoutingDataSource.put(pKey, zfRoutingDataSource);
        return zfRoutingDataSource;
    }
    public ZfRoutingDataSource get(String pKey) {
        return Optional.<ZfRoutingDataSource>ofNullable(mRoutingDataSource.get(pKey)).
                orElseThrow(()->new ServiceException("没有找到key为"+pKey+"的数据源"));
    }
}
